//
//  MMScrollPreviewView.m
//  MemeMaker
//
//  Created by Phan Quang Ha on 7/18/13.
//  Copyright (c) 2013 soyo. All rights reserved.
//

#import "MMScrollPreviewView.h"
#import <QuartzCore/QuartzCore.h>

#define DEFAULT_RATE 4

@interface MMScrollPreviewView ()
{
    CGRect bigRect;
    CGRect smallRect;
    
    CGRect viewingRect;
    CGRect thumbnailRect;
    
    CALayer *animatingLayer;
    CALayer *viewingLayer;
}

@end

@implementation MMScrollPreviewView
@synthesize btnPlus, btnMinus;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    [self.currentImage drawInRect:thumbnailRect];
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGLayerRef scrollLayer;
    scrollLayer = CGLayerCreateWithContext(context, rect.size, NULL);
    CGContextRef scrollContext = CGLayerGetContext(scrollLayer);
    
    UIColor *overallColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5];
    CGContextSetFillColorWithColor(scrollContext, overallColor.CGColor);
    CGContextFillRect(scrollContext, rect);
    CGContextClearRect(scrollContext, viewingRect);
    
    CGContextDrawLayerInRect(context, rect, scrollLayer);
    
    CGLayerRelease(scrollLayer);
    
    
}

- (void) animateChangeBorderWidthWidthDuration:(CGFloat)duration
{
    CABasicAnimation *borderWidthAnimation = [CABasicAnimation animationWithKeyPath:@"borderWidth"];
    [borderWidthAnimation setFromValue:[NSNumber numberWithFloat:3.0f]];
    [borderWidthAnimation setToValue:[NSNumber numberWithFloat:1.0f]];
    [borderWidthAnimation setDuration:duration];
    
    [animatingLayer addAnimation:borderWidthAnimation forKey:@"borderWidth"];
    
    animatingLayer.frame = CGRectMake(thumbnailRect.origin.x, thumbnailRect.origin.y - 1, thumbnailRect.size.width, thumbnailRect.size.height+1);
}

- (void)setNeedsDisplay
{
    [super setNeedsDisplay];
    
}

- (id)initWithBigRect:(CGRect)rect1 smallRect:(CGRect)rect2 andImage:(UIImage *)img
{
    CGFloat width = rect2.size.width / DEFAULT_RATE;
    CGFloat height = rect2.size.height;
    CGFloat thumbnailHeight = rect1.size.height * width/rect1.size.width;
    
    if (self = [super initWithFrame:CGRectMake(-width, 0.0, width, height)]) {
        bigRect = rect1;
        smallRect = rect2;
        
        thumbnailRect = CGRectMake(0, smallRect.size.height/2 - thumbnailHeight/2 - 10, width, thumbnailHeight);
        viewingRect = CGRectMake(0, thumbnailRect.origin.y, width, rect2.size.height/DEFAULT_RATE);
        
        self.currentImage = img;
        if (!btnMinus) {
            btnMinus = [UIButton buttonWithType:UIButtonTypeCustom];
            [btnMinus setFrame:CGRectMake(1.0, self.frame.size.height - 31, 39, 30)];
            [btnMinus setImage:[UIImage imageNamed:@"ico_minus.png"] forState:UIControlStateNormal];
            [btnMinus addTarget:self action:@selector(minusView) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:btnMinus];
        }
        
        if (!btnPlus) {
            btnPlus = [UIButton buttonWithType:UIButtonTypeCustom];
            [btnPlus setFrame:CGRectMake(41.0, self.frame.size.height - 31, 38, 30)];
            [btnPlus setImage:[UIImage imageNamed:@"ico_plus.png"] forState:UIControlStateNormal];
            [btnPlus addTarget:self action:@selector(plusView) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:btnPlus];
        }
        
        if (!animatingLayer) {
            animatingLayer = [CALayer layer];
            animatingLayer.frame = thumbnailRect;
            animatingLayer.backgroundColor = [UIColor clearColor].CGColor;
            
            animatingLayer.borderWidth = 1.0f;
            animatingLayer.borderColor = [UIColor blueColor].CGColor;
            [self.layer addSublayer:animatingLayer];
        }
    }
    return self;
}

- (void) setBigRect:(CGRect)rect andImage:(UIImage *)img
{
    CGFloat newThumbHeight = rect.size.height * thumbnailRect.size.width / rect.size.width;
    CGFloat newThumbY = smallRect.size.height / 2 - newThumbHeight/2 - 10;
    CGFloat diffY =  newThumbY - thumbnailRect.origin.y;
    thumbnailRect = CGRectMake(0, newThumbY, thumbnailRect.size.width, newThumbHeight);
    viewingRect = CGRectMake(0, viewingRect.origin.y + diffY, viewingRect.size.width, viewingRect.size.height);
    self.currentImage = img;
    [self animateChangeBorderWidthWidthDuration:0.3];
    [self setNeedsDisplay];
}

- (void) plusView {
    if (thumbnailRect.size.height < self.frame.size.height - 60) {
        if (_delegate && [_delegate respondsToSelector:@selector(changedWithHeight:)]) {
            [_delegate changedWithHeight:20.0f];
        }
    }
    
    [self setNeedsDisplay];
}

- (void) minusView {
    if (thumbnailRect.size.height > bigRect.size.height * (smallRect.size.width/DEFAULT_RATE)/bigRect.size.width) {
        if (_delegate && [_delegate respondsToSelector:@selector(changedWithHeight:)]) {
            
            [_delegate changedWithHeight:-20.0f];
            
            if (viewingRect.origin.y + viewingRect.size.height > thumbnailRect.size.height + thumbnailRect.origin.y) {
                CGFloat changedValue = (viewingRect.origin.y + viewingRect.size.height) - (thumbnailRect.size.height + thumbnailRect.origin.y);
                viewingRect.origin.y = thumbnailRect.origin.y + thumbnailRect.size.height - viewingRect.size.height;
                if ([_delegate respondsToSelector:@selector(didChangedParentHeight:withRate:)]) {
                    [_delegate didChangedParentHeight:changedValue withRate:DEFAULT_RATE];
                }
            
            }
        }
    }
    
    [self setNeedsDisplay];
//    [self animateChangeBorderWidthWidthDuration:0.3];
}
//- (void) saveToWorkspace:(UIButton *)btn
//{
//    if (_delegate && [_delegate respondsToSelector:@selector(needSaveCurrentImage)]) {
//        [_delegate needSaveCurrentImage];
//    }
//}
//- (void) backToWorkspace:(UIButton *)btn
//{
//    if (_delegate && [_delegate respondsToSelector:@selector(cancelDrawingImage)]){
//        [_delegate cancelDrawingImage];
//    }
//}
#pragma mark - Touch
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint previousPoint = [touch previousLocationInView:self];
    CGPoint currentPoint = [touch locationInView:self];
    
    CGFloat diffHeight = currentPoint.y - previousPoint.y;
    
    if (diffHeight < 0 && (viewingRect.origin.y + diffHeight) < thumbnailRect.origin.y) {
        return;
    }
    if (diffHeight > 0 && (viewingRect.origin.y + viewingRect.size.height + diffHeight) > (thumbnailRect.size.height + thumbnailRect.origin.y)) {
        return;
    }
    viewingRect.origin.y = viewingRect.origin.y + diffHeight;
    [self setNeedsDisplay];
    
    if (_delegate && [_delegate respondsToSelector:@selector(didChangeOrigin:withRate:)]) {
        [_delegate didChangeOrigin:diffHeight withRate:DEFAULT_RATE];
    }
}

@end
